package com.sn.springboot_netty.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Author fyy
 * @Description 网络文件下载
 * @Date 2020/5/28 11:24
 */
public class FileDownloadUtil {

    private static Logger logger = LoggerFactory.getLogger(FileDownloadUtil.class);
    private static final String filePath = TemplateWordUtil.class.getResource("/static/alarm_img").getPath();

    /**
     * @Author fyy
     * @Description 文件下载
     * @Date 2020/5/28 11:25
     */
    public static void downFile(HttpServletResponse response,String fName){
        String fileName = fName + ".zip";

        File file = new File(filePath+"/"+fileName);
        if(file.exists()){
            response.setContentType("application/gorce-download");
            response.addHeader("Content-disposition","attachment;fileName=\""+ fileName +"\"");
            response.setContentLength((int) file.length());
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {

            } finally {
                try {
                    if (bis != null) bis.close();
                    if (fis != null) fis.close();
                } catch (IOException e) {

                }
            }
        }
        file.delete();
    }

}
